import fs from "node:fs/promises";
import path from "node:path";

interface SaveFigmaMinOptions {
  rawPath: string;
  minPath: string;
  summaryPath?: string;
}

const WORKFLOW_ROOT = path.resolve(__dirname, "..", "..");

export async function saveFigmaMin(options: SaveFigmaMinOptions) {
  const rawStats = await fs.stat(resolvePath(options.rawPath));
  const minStats = await fs.stat(resolvePath(options.minPath));
  const summary = {
    rawBytes: rawStats.size,
    minBytes: minStats.size,
    reduction: Number((1 - minStats.size / Math.max(rawStats.size, 1)).toFixed(2)),
    minPath: resolvePath(options.minPath),
  };

  if (options.summaryPath) {
    await fs.writeFile(resolvePath(options.summaryPath), JSON.stringify(summary, null, 2), "utf-8");
  }

  return summary;
}

function resolvePath(target: string): string {
  return path.isAbsolute(target) ? target : path.join(WORKFLOW_ROOT, target);
}
